package net.wicp.tams.duckula.server.connector;

import javax.management.remote.JMXConnector;

import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.connector.beans.CusDynaBean;
import net.wicp.tams.common.connector.executor.IBusiApp;
import net.wicp.tams.commons.apiext.JmxUtil;
import net.wicp.tams.commons.apiext.StringUtil;
import net.wicp.tams.duckula.server.service.MBeanUtil;

@Service(value = "TaskStop")
@Slf4j
public class TaskStop implements IBusiApp {
	@Override
	public CusDynaBean exe(CusDynaBean inputBean, CusDynaBean outBeanOri) {
		long begintime = System.currentTimeMillis();
		String taskId = inputBean.getStrValueByName("taskId");
		int jmxPort = Integer.parseInt(inputBean.getStrValueByName("jmxPort"));
		jmxPort = jmxPort > 0 ? jmxPort : StringUtil.buildPort(taskId);
		log.info("opt:stop,taskId:{},jmxPort:{}", taskId, jmxPort);
		JMXConnector conn = JmxUtil.connect(jmxPort);
		MBeanUtil.stopTask(conn);
		try {
			conn.close();
		} catch (Exception e) {
			// 都停了任务任务肯定抛异常
			// log.error("stop error", e);
		}
		outBeanOri.set("usetimes", String.valueOf(System.currentTimeMillis() - begintime));
		return outBeanOri;
	}
}
